package mammuthus.slave

import mammuthus.docker.protocal._
import mammuthus.docker.protocal.CreateContainerResponse
import mammuthus.docker.protocal.StopContainerRequest
import mammuthus.docker.protocal.CreateContainerRequest
import mammuthus.docker.protocal.StartContainerRequest
import mammuthus.protocal.{DockerInstancePort, DockerInstanceDetail}

/**
 * 5/10/15 WilliamZhu(allwefantasy@gmail.com)
 */
trait DockerActor {
  this: SlaveActor =>
  def dockerProcess(item: Any) = {
    item match {
      case CreateContainerRequest(hostName, name, image) => {
        logger.info(s"accept CreateContainerRequest request $hostName $name $image")
        val res = dockerClient.createContainer(name, image)
        val kk = CreateContainerResponse(hostName, true, res._1, res._2, "")
        logger.info(s"finish CreateContainerRequest request $hostName $name $image")
        kk
      }
      case StartContainerRequest(hostName, nameOrId: String) => {
        logger.info(s"accept StartContainerRequest request $hostName $nameOrId")
        dockerClient.startContainer(nameOrId)
        val kk = StartContainerRequest(hostName, nameOrId)
        logger.info(s"finish StartContainerRequest request $hostName $nameOrId")
        kk
      }
      case StopContainerRequest(hostName, nameOrId: String) => {
        logger.info(s"accept StopContainerRequest request $hostName $nameOrId")
        dockerClient.stopContainer(nameOrId)
        val kk =  StopContainerRequest(hostName, nameOrId)
        logger.info(s"finish StopContainerRequest request $hostName $nameOrId")
        kk
      }
      case ListContainerRequest(hostName) => {
        logger.info("accept ListContainerRequest request")
        val res = dockerClient.listContainer.map {
          f =>
            val ports = f.getPorts.map(k => DockerInstancePort(k.getIp, k.getPrivatePort, k.getPublicPort, k.getType)).toList
            DockerInstanceDetail(hostName, f.getId, f.getNames.toList, f.getImage, f.getCreated, f.getStatus, f.getCommand, ports)
        }.toList
        val kk =  ListContainerResponse(hostName, res)
        logger.info(s"finish ListContainerRequest request $hostName")
        kk
      }
    }
  }
}
